package com.quanyan.club.web;

import com.quanyan.BaseRequest;
import com.quanyan.api.APIResponse;
import com.quanyan.api.enums.ApiResponseEnum;
import com.quanyan.club.constants.ClubConstants;
import com.quanyan.club.entity.RespClubBaseInfo;
import com.quanyan.club.entity.db.TbClub;
import com.quanyan.club.entity.vo.req.ReqClub;
import com.quanyan.club.entity.vo.req.ReqClubPage;
import com.quanyan.club.entity.vo.req.ReqClubRecommend;
import com.quanyan.club.entity.vo.req.ReqClubSearch;
import com.quanyan.club.entity.vo.resp.*;
import com.quanyan.club.mapper.TbClubMapper;
import com.quanyan.club.service.ClubMemberService;
import com.quanyan.club.service.ClubSearchBizService;
import com.quanyan.club.service.ClubService;
import com.quanyan.club.service.CppService;
import com.quanyan.common.Plugin.PageObj;
import com.quanyan.common.enums.BaseEnum;
import com.quanyan.common.exception.BizException;
import com.quanyan.common.utils.CommonUtils;
import com.quanyan.common.utils.StringUtil;
import com.quanyan.mq.client.response.MqResponse;
import com.quanyan.redisCluster.config.RedisTemplate;
import com.quanyan.redisCluster.utils.RedisConstants;
import com.quanyan.redisCluster.utils.RedisKey;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by zhuo.shi on 2016/5/30.
 * 功能：
 * 1. 创建俱乐部
 * 2. 设置（编辑）俱乐部
 * 3. 显示俱乐部详细信息
 * 4. 我创建的俱乐部列表
 * 5. 我加入的俱乐部列表
 * 6. 推荐的俱乐部列表
 * 7. 搜索俱乐部
 */
@RestController
@RequestMapping(value="/api/club/system")
public class ClubController extends BaseController{

    @Autowired
    private ClubService clubService;
    @Autowired
    private TbClubMapper clubMapper;
    @Autowired
    private CppService cppService;
    @Autowired
    private ClubMemberService clubMemberService;
    @Autowired
    private ClubSearchBizService clubSearchBizService;
    @Autowired
    private RedisTemplate redisTemplate;

    @RequestMapping(value = "/getClubFAQLink")
    public APIResponse getClubFAQLink(@RequestBody Map map){
        if (!map.containsKey("hrefNo")){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(
                clubService.getClubFAQLink(MapUtils.getIntValue(map, "hrefNo")));
    }

    /**
     * 俱乐部类型列表
     * @return
     */
    @RequestMapping(value="/type", method = RequestMethod.POST)
    public APIResponse<List<RespClubType>> type(@RequestBody BaseRequest baseRequest){
        List<RespClubType> clubTypeList = clubService.listClubType(baseRequest.getVer());
        return APIResponse.returnSuccess(clubTypeList);
    }

    /**
     * 俱乐部系统LOGO列表
     * @return
     */
    @RequestMapping(value = "/logo", method = RequestMethod.POST)
    public APIResponse<List<RespClubSystemLogo>> logo(){

        List<RespClubSystemLogo> clubSystemLogoList = clubService.listClubSystemLogo();
        return APIResponse.returnSuccess(clubSystemLogoList);
    }

    /**
     * 新建俱乐部
     * @param reqClub   俱乐部请求对象<code>com.quanyan.club.entity.vo.req.ReqClub</code>
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public APIResponse addClub(@RequestBody ReqClub reqClub,
                               HttpServletRequest request){
        //权限检查
        int uid = getUid(request, true);
        if (reqClub.getCityId() == null || reqClub.getCityId() <= 0
                || reqClub.getDistrictId() == null || reqClub.getDistrictId() <= 0){
            return APIResponse.returnFail("俱乐部城市或区域不能为空！");
        }
        if (StringUtil.isBlankOrNull(reqClub.getClubName())){
            return APIResponse.returnFail("俱乐部名称不能为空！");
        }
        if (StringUtil.isBlankOrNull(reqClub.getSportName())){
            return APIResponse.returnFail("俱乐部运动类型名不能为空！");
        }
        if(!CommonUtils.validName(reqClub.getClubName()))
        {
            return APIResponse.returnFail("俱乐部名称只允许输入中文，英文，数字");
        }
        RedisKey limitKey = new RedisKey(RedisConstants.CLUB_FAMILY_KEY, ClubConstants.CREATE_CLUB_LIMIT + uid);
        if(redisTemplate.exists(limitKey)) {
            throw new BizException("重复提交！");
        }else {
            redisTemplate.setWithExpireTime(limitKey, uid, 100);
        }
        try {
            RespClubBaseInfo respClubBaseInfo = clubService.saveClub(uid, reqClub);
            redisTemplate.delteKey(limitKey);
            return APIResponse.returnSuccess(respClubBaseInfo);
        }catch (Exception e){
            redisTemplate.delteKey(limitKey);
            throw new BizException(e.getMessage());
        }
    }

    /**
     * 俱乐部详细信息
     */
   @RequestMapping(value = "/detail")
   public APIResponse<RespClubDetail> showClubDetail(@RequestBody Map map, HttpServletRequest request){
       int uid = getUid(request, false);
       if (!map.containsKey("clubId")){
           return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
       }
       TbClub club = clubMapper.selectByPrimaryKey(MapUtils.getInteger(map, "clubId"));
       if(null == club) {
           return APIResponse.returnFail("此俱乐部已解散！");
       }
       return APIResponse.returnSuccess(clubService.queryClubDetail(uid, (int)map.get("clubId")));
   }

    /**
     * 编辑俱乐部
     * @param reqClub
     * @return
     */
    @RequestMapping(value = "/edit", method = RequestMethod.POST, produces = {"application/json; charset=UTF-8"})
    public APIResponse editClub(@RequestBody ReqClub reqClub, HttpServletRequest request){
        int uid = getUid(request, true);
        //权限检查
        if(!clubMemberService.isClubAdminMember(uid, reqClub.getClubId())){
            return APIResponse.returnFail(ApiResponseEnum.PERMISSION_DENIED);
        }
        if(!StringUtil.isBlankOrNull(reqClub.getClubName()) && !CommonUtils.validName(reqClub.getClubName()))
        {
            return APIResponse.returnFail("俱乐部名称只允许输入中文，英文，数字");
        }
        BaseEnum baseEnum = clubService.updateClub(uid, reqClub);
        if (baseEnum.isSuccess()){
            return APIResponse.returnSuccess();
        }
        return APIResponse.returnFail(baseEnum);
    }

    /**
     * 我创建的俱乐部列表
     * @param reqClubPage
     * @return
     */
    @RequestMapping(value = "/mycreate/list", method = RequestMethod.POST)
    public APIResponse<PageObj<List<RespClubBaseInfo>>> listMyClubs(@RequestBody ReqClubPage reqClubPage,
                                                                    HttpServletRequest request){
        Map<String, Object> paramMap = reqClubPage.getParamMap();
        if (paramMap == null || paramMap.isEmpty()){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int type = Integer.valueOf(String.valueOf(paramMap.get("type")));
        if (type != 1){    //必须为：1 我创建的
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        int uid = getUid(request, true);
        List<RespClubBaseInfo> respClubBaseInfoList = clubService.listMyCreateClubs(uid, reqClubPage);
        int total = clubService.countMyCreateClubs(uid);
        return APIResponse.returnSuccess(PageObj.create(total, reqClubPage.getPageNum() + 1, reqClubPage.getPageSize(), respClubBaseInfoList));
    }

    /**
     * 我加入的俱乐部列表
     * @param reqClubPage
     * @return
     */
    @RequestMapping(value = "/myjoined/list", method = RequestMethod.POST)
    public APIResponse<PageObj<List<RespClubBaseInfo>>> listMyJoinedClubs(@RequestBody ReqClubPage reqClubPage,
                                                                          HttpServletRequest request){
        Map<String, Object> paramMap = reqClubPage.getParamMap();
        if (paramMap == null || paramMap.isEmpty()){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int type = Integer.valueOf(String.valueOf(paramMap.get("type")));
        if (type != 2){    //必须为：2 我加入的
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_INVALID);
        }
        int uid = getUid(request, true);
        List<RespClubBaseInfo> respClubBaseInfoList = clubService.listMyJoinedClubs(uid, reqClubPage);
        int total = clubService.countMyJoinedClubs(uid, reqClubPage);
        return APIResponse.returnSuccess(PageObj.create(total, reqClubPage.getPageNum() + 1, reqClubPage.getPageSize(), respClubBaseInfoList));
    }

    @RequestMapping(value = "/myclubs/all")
    public APIResponse listMyAllClubs(@RequestBody Map map, HttpServletRequest request){
        int uid = getUid(request, true);
        return APIResponse.returnSuccess(clubService.listMyAllClubs(uid));
    }

    @RequestMapping(value = "/user/clublist")
    public APIResponse listUserAllClubs(@RequestBody Map map, HttpServletRequest request){
        Integer uid = MapUtils.getInteger(map, "uid");
        if (uid == null){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        return APIResponse.returnSuccess(clubService.listMyAllClubs(uid));
    }

    /**
     * 我的俱乐部列表，包含我加入的和创建的
     */
    @RequestMapping(value = "/myclubs", method = RequestMethod.POST)
    public APIResponse listMyClubs(HttpServletRequest request){

        int uid = getUid(request, true);

        ReqClubPage reqClubPage = new ReqClubPage();
        Map<String, Object> map = new HashMap<>();
        map.put("type", 1);
        reqClubPage.setParamMap(map);
        List<RespClubBaseInfo> myCreateClubs = clubService.listMyCreateClubs(uid, reqClubPage);
        map.clear();
        map.put("type", 2);
        reqClubPage.setParamMap(map);
        List<RespClubBaseInfo> myJoinedClubs = clubService.listMyJoinedClubs(uid, reqClubPage);

        RespMyClubs myClubs = new RespMyClubs();
        myClubs.setMyCreateClubs(myCreateClubs);
        myClubs.setMyJoinedClubs(myJoinedClubs);

        return APIResponse.returnSuccess(myClubs);
    }

    @RequestMapping(value = "/myManageClubList")
    public APIResponse getMyManageClubList(HttpServletRequest request){
        Integer uid = getUid(request, true);
        return APIResponse.returnSuccess(
                clubService.getMyManageClubList(uid));
    }

    /**
     * 搜索俱乐部
     */
    @RequestMapping(value = "/search/list", method = RequestMethod.POST)
    public APIResponse<PageObj<List<RespClubBaseInfo>>> searchClubs(@RequestBody ReqClubSearch reqClubSearch,
                                                                     HttpServletRequest request){
        Integer uid = getUid(request, false);
        return APIResponse.returnSuccess(clubService.searchClubs(uid, reqClubSearch));
    }

    @RequestMapping(value = "/clubSearch", method = RequestMethod.POST)
    public APIResponse<PageObj<List<RespClubBaseInfo>>> clubSearch(@RequestBody ReqClubSearch reqClubSearch,
                                                                    HttpServletRequest request){
        Integer uid = getUid(request, false);
        if (reqClubSearch.getLat() == null && reqClubSearch.getLng() == null){
            reqClubSearch.setLng(116.41667);
            reqClubSearch.setLat(39.91667);
            //throw new BizException("获取不到经纬度！");
        }
        return APIResponse.returnSuccess(clubSearchBizService.searchClubs(uid, reqClubSearch));
    }

    /**
     * 俱乐部推荐列表
     * @return      返回推荐的俱乐部列表，返回空列表说明已经有加入的或者创建的俱乐部
     */
    @RequestMapping(value = "/recommend/list")
    public APIResponse<List<RespClubBaseInfo>> getRecommendClubs(@RequestBody ReqClubRecommend reqClubRecommend, HttpServletRequest request){
        int uid = getUid(request, false);
        return APIResponse.returnSuccess(clubService.getRecommendClubs(uid, reqClubRecommend));
    }

    @RequestMapping(value = "/cities/list")
    public APIResponse showCityList(@RequestBody Map map){
        Double lat = MapUtils.getDouble(map, "lat");
        Double lng = MapUtils.getDouble(map, "lng");
        return APIResponse.returnSuccess(clubService.listCity(lat, lng));
    }


    /**
     * 获取俱乐部属性列表
     * @return
     */
    @RequestMapping(value = "property",method = RequestMethod.POST)
    public APIResponse<List<RespClubProperty>> getClubPropertyList(){
        List<RespClubProperty> list = this.clubService.listClubProperty();
        return APIResponse.returnSuccess(list);
    }

    /**
     * 获取开通省市区列表
     * @return
     */
    @RequestMapping(value = "situation",method = RequestMethod.POST)
    public APIResponse<RespSituation> getSituationList(@RequestBody Map map){
        if(null == map.get("lastUpdateTime")){
            return APIResponse.returnFail("请传入必要参数！！！");
        }

        long lastUpdateTime = Long.valueOf( String.valueOf( map.get("lastUpdateTime")));
        RespSituation respSituation = this.clubService.getSituationList(lastUpdateTime);
        return APIResponse.returnSuccess(respSituation);
    }

    /**
     * 俱乐部积分排名列表
     */
    @RequestMapping(value = "/ranking/list")
    public APIResponse getClubRankingList(@RequestBody ReqClubPage reqClubPage){
        Map<String, Object> paramMap = reqClubPage.getParamMap();
        if (paramMap == null || paramMap.isEmpty() || !paramMap.containsKey("type")){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        int pageNo = reqClubPage.getPageNum() + 1;
        int pageSize = reqClubPage.getPageSize();
        int type = Integer.valueOf(paramMap.get("type").toString());
        Integer sportTypeId = MapUtils.getInteger(paramMap, "sportTypeId");
        PageObj pageObj = new PageObj();
        if (type == 1){ //全国排名
            pageObj = clubService.getClubRankingList(sportTypeId, null, pageNo, pageSize);
        }
        if (type == 2){//城市排名
            if (!paramMap.containsKey("cityId")){
                return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
            }
            int cityId = Integer.valueOf(paramMap.get("cityId").toString());
            pageObj = clubService.getClubRankingList(sportTypeId, cityId, pageNo, pageSize);
        }
        return APIResponse.returnSuccess(pageObj);
    }

    /**
     * 获取城市区域列表
     * @param map
     * @return
     */
    @RequestMapping("districtList")
    public APIResponse<RespClubCity> districtList(@RequestBody Map map){
        if(null == map.get("cityId")){
            return APIResponse.returnFail("请传入必要参数");
        }
        int cityId = (int) map.get("cityId");
        RespClubCity respClubCity = this.clubService.getCityDistrictList(cityId);

        return APIResponse.returnSuccess(respClubCity);
    }

    /**
     * 获取俱乐部二维码
     * @param map
     * @return
     */
    @RequestMapping("clubQRCode")
    public APIResponse<RespClubQRCodeInfo> clubQRCode(@RequestBody Map map){
        int clubId;
        if(map.containsKey("clubId")){
            clubId = (int) map.get("clubId");
        }else{
            return APIResponse.returnFail("请传入必要参数");
        }
        RespClubQRCodeInfo respClubQRCodeInfo = this.clubService.getClubQRCode(clubId);
        if (respClubQRCodeInfo == null) {
            return APIResponse.returnFail("该俱乐部不存在");
        }else{
            return APIResponse.returnSuccess(respClubQRCodeInfo);
        }
    }


    @RequestMapping("test")
    public APIResponse test(){
        MqResponse mqResponse = this.clubService.test("");
        return APIResponse.returnSuccess(mqResponse);
    }

    @RequestMapping("/IM/addGroupMember")
    public APIResponse addIMGroupMember(@RequestBody Map map){
        Integer groupUid = MapUtils.getInteger(map, "groupUid");
        Integer uid = MapUtils.getInteger(map, "uid");
        String groupid = MapUtils.getString(map, "groupid");
        Integer extid = MapUtils.getInteger(map, "extid");
        if(extid == null)
        {
            extid = 0;
        }
        if (groupid == null || uid == null ||
                StringUtil.isBlankOrNull(groupid)){
            return APIResponse.returnFail(ApiResponseEnum.PARAMETER_CANT_BE_EMPTY);
        }
        boolean result = cppService.addOrDelIMGroupMember(groupUid,extid, groupid, Arrays.asList(uid), true);
        if (result){
            return APIResponse.returnSuccess();
        }else {
            return APIResponse.returnFail("加入群聊失败！");
        }
    }
}
